package org.oschina.api.index.queue;

import java.util.List;

import javax.annotation.PreDestroy;
import org.oschina.Constants;
import org.oschina.api.index.dao.IndexDAO;
import org.oschina.api.index.model.IndexMajorUpdateBean;
import org.oschina.queue.BaseQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 索引主键更新队列
 */
@Component
public class IndexMajorUpdateQueue extends BaseQueue {

	private final static Logger logger=LoggerFactory.getLogger(IndexMajorUpdateQueue.class);
	
	@Autowired
	private IndexDAO indexDAO;
	
	private final int UPDATE_TIME=10; //更新时间
	
	@Scheduled(fixedDelay=1000)
	private synchronized void handle()
	{
		IndexMajorUpdateBean bean=(IndexMajorUpdateBean)get(Constants.QUEUE_INDEX_MAJOR_UPDATE, IndexMajorUpdateBean.class);
		push(bean);
		
		if(isUpdate())
			update();
	}

	private void push(IndexMajorUpdateBean indexMajorUpdateBean)
	{
		if(indexMajorUpdateBean==null)
			return;
		
		getCacheHelper().lpush(getKey(), indexMajorUpdateBean, getTimeout());
	}
	
	private boolean isUpdate()
	{
		return (getCacheHelper().llen(getKey())!=0 && isUpdate(UPDATE_TIME));
	}
	
	private void update()
	{
		List<IndexMajorUpdateBean> args=getCacheHelper().lget(getKey(), 0, -1, IndexMajorUpdateBean.class);
		getCacheHelper().del(getKey());
		
		for(IndexMajorUpdateBean bean:args)
			logger.info("主键为'{}'的索引已增加'{}'",bean.getId(),bean.getCount());
		indexDAO.batchUpdate(args);
	}
	
	private String getKey()
	{
		return Constants.CACHE_INDEX_MAJOR_UPDATE;
	}
	
	private int getTimeout()
	{
		return Constants.TIMEOUT_INDEX;
	}
	
	@PreDestroy
	private void destroy()
	{
		update();
	}
}